//
//  ESRightViewController.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/4.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESRightViewController.h"

#import "ESCheckPost.h"
#import "ESNavigationController.h"
#import "ESRegisterVC.h"
#import "ESLoginVC.h"
#import "UMSocial.h"

@interface ESRightViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *loginLabel;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *weiboBtn;

@end

@implementation ESRightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if ([BmobUser getCurrentUser]) {
        //           [self configUserName];
        [self hasLogin];
    }
    
}

- (void)didShow
{
   [UIView transitionWithView:self.iconView duration:1.0 options: UIViewAnimationOptionTransitionFlipFromLeft  animations:^{
       self.iconView.image = [UIImage imageNamed:@"smile"];
       if (![BmobUser getCurrentUser]) {
            self.loginLabel.text = @"开心从此开始";
       }
   } completion:^(BOOL finished) {
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           [UIView transitionWithView:self.iconView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
//               self.loginLabel.text = @"立即登录";
               self.iconView.image = [UIImage imageNamed:@"default_avatar"];
               if ([BmobUser getCurrentUser]) {
                   [self configUserProfile];
               }
           } completion:nil];
       });
   }];
}

- (IBAction)login:(UIButton *)sender {
    
    if ([BmobUser getCurrentUser]) {
        [self logout];
    } else {
        ESLoginVC *lgVc = [[ESLoginVC alloc] init];
        [self addChildViewController:lgVc];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:lgVc];
        nav.navigationBar.hidden = YES;
        [self presentViewController:nav animated:YES completion:nil];
        [ESNotificationCenter addObserver:self selector:@selector(hasLogin) name:@"UserOK" object:nil];
    }
    
    
}

- (void)configUserName {
    self.loginLabel.text = [BmobUser getCurrentUser].username;
    self.loginBtn.enabled = NO;
    [self.loginBtn setTitle:[BmobUser getCurrentUser].username forState:UIControlStateDisabled];
}

- (void)hasLogin {
    self.loginLabel.text = [BmobUser getCurrentUser].username;
    [self.loginBtn setTitle:@"注销" forState:UIControlStateNormal];
    _weiboBtn.hidden = YES;
}

- (IBAction)register:(UIButton *)sender {
}


- (IBAction)logout {
    [BmobUser logout];
    self.loginLabel.text = @"开心从此开始";
    self.iconView.image = [UIImage imageNamed:@"default_avatar"];
    self.loginBtn.enabled = YES;
    [self.loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
    _weiboBtn.hidden = NO;
    
}



//15037337914
- (IBAction) weiboLogin:(UIButton *)sender {
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            //得到的新浪微博授权信息，生成NSDictionary
            NSDictionary *dic = @{@"access_token":snsAccount.accessToken,@"uid":snsAccount.usid,@"expirationDate":snsAccount.expirationDate};
            //通过授权信息注册登录
            [BmobUser loginInBackgroundWithAuthorDictionary:dic
                                                   platform:BmobSNSPlatformSinaWeibo
                                                      block:^(BmobUser *user, NSError *error) {
                                                          
                                                          BmobUser *bUser = [BmobUser getCurrentUser];
                                                          //更新number为30
                                                          [bUser setObject:snsAccount.userName forKey:@"username"];
                                                          [bUser updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                                              if (!isSuccessful) {
                                                                  ESLog(@"error %@",[error description]);
                                                              }
                                                              
                                                          }];
                                                          
                                                          //查找第三方账号信息在UserDetail是否存在
                                                          BmobQuery   *bquery = [BmobQuery queryWithClassName:@"UserDetail"];
                                                          [bquery whereKey:@"userId" equalTo:bUser.objectId];
                                                          [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
                                                              
                                                              
                                                              if (array.count == 0) {//不存在
                                                                  
                                                                  //存储第三方账号的详细信息
                                                                  BmobObject  *userDetail = [BmobObject objectWithClassName:@"UserDetail"];
                                                                  NSDictionary *dic = @{@"userId":bUser.objectId,
                                                                                        @"platformName":snsAccount.platformName,
                                                                                        @"expirationDate":snsAccount.expirationDate,
                                                                                        @"userName":snsAccount.userName,
                                                                                        @"iconURL":snsAccount.iconURL,
                                                                                        @"profileURL":snsAccount.profileURL,
                                                                                        @"accessToken":snsAccount.accessToken,
                                                                                        @"userIdThird":snsAccount.usid
                                                                                        };
                                                                  [userDetail saveAllWithDictionary:dic];
                                                                  [userDetail saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                                                      if (isSuccessful) {
                                                                          //创建成功后的动作
//                                                                          ESLog(@"isSuccessful");
                                                                          [self configUserProfile];
                                                                      } else if (error){
                                                                          //发生错误后的动作
                                                                          ESLog(@"%@",error);
                                                                      } else {
                                                                          ESLog(@"Unknow error");
                                                                      }
                                                                  }];
                                                                  
                                                                  
                                                              } else {//存在
                                                                  [self configUserProfile];
                                                              }
                                                              
                                                              
                                                          }];
                                                          
                                                          
                                                          
//                                                          ESLog(@"%@",bUser);
                                                      }];
            

            
        }
    });
}

- (void) configUserProfile {
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"UserDetail"];
    [bquery whereKey:@"userId" equalTo:[BmobUser getCurrentUser].objectId];
    
    
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (BmobObject *obj in array) {
            NSString *iconURL = [obj objectForKey:@"iconURL"];
            NSString *userName = [obj objectForKey:@"userName"];
            self.loginLabel.text = userName;
            [_iconView sd_setImageWithURL:[NSURL URLWithString:iconURL]];
//            [self configUserName];
            [self hasLogin];
        }
    }];
}

@end
